import { Body, Controller, Delete, Get, Param, ParseIntPipe, Post, Put, Req } from '@nestjs/common';
import { DeviceParamsFieldService } from './device-params-field.service';
import { ResponseUtilService } from '@app/response-util';
import { DtoPipe } from '../../pipe/dto/dto.pipe';
import PageDto from './dto/page.dto';
import CreateDto from './dto/create.dto';
import { ReqAttrs } from '../../constant';
import UpdateDto from './dto/update.dto';

@Controller('/deviceParamsField')
export class DeviceParamsFieldController {
    constructor(
        private readonly service:DeviceParamsFieldService
    ){}

    @Get('options')
    async list() {
        const result = await this.service.options()
        return ResponseUtilService.successRes(result)
    }

    @Post('page')
    async page(@Body(new DtoPipe({skipMissingProperties : true})) dto:PageDto) {
        const result = await this.service.page(dto)

        return ResponseUtilService.successRes(result)

    }

    @Post('add')
    async add(@Body(new DtoPipe()) dto:CreateDto, @Req() req) {
        const memberId = req[ReqAttrs.MEMBER_ID]
        try {
            const r = await this.service.add(dto, memberId)
            return r ? ResponseUtilService.successRes() : ResponseUtilService.failRes()
        } catch (error) {
            return ResponseUtilService.failRes(error.message)
        }
    }

    @Put('update')
    async update(@Body(new DtoPipe()) dto:UpdateDto) {
        try {
            const r = await this.service.update(dto)
            return r ? ResponseUtilService.successRes() : ResponseUtilService.failRes()
        } catch (error) {
            return ResponseUtilService.failRes(error.message)
        }
    }

    @Delete('delete/:id')
    async del(@Param('id', ParseIntPipe) id:number, @Req() req) {
        if(id < 1) return null
        try {
            const r = await this.service.del(id)
            return r ? ResponseUtilService.successRes() : ResponseUtilService.failRes()
        } catch (error) {
            return ResponseUtilService.failRes(error.message)
        } 
    }
}
